package middleware

import (
	"fitness/internal/dao"
	"github.com/duke-git/lancet/v2/slice"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
	"strings"
)

type Rbac struct {
	SysRoleDao     *dao.SysRoleDao
	SysRoleMenuDao *dao.SysRoleMenuDao
}

func NewRbac(SysRoleDao *dao.SysRoleDao, SysRoleMenuDao *dao.SysRoleMenuDao) *Rbac {
	return &Rbac{
		SysRoleDao:     SysRoleDao,
		SysRoleMenuDao: SysRoleMenuDao,
	}
}

func (rbac *Rbac) RbacAuth(perm string) gin.HandlerFunc {
	return func(c *gin.Context) {
		roleStr := c.GetString("role_id")
		var flag bool
		if roleStr != "" {
			roles := strings.Split(roleStr, ",")
			for _, roleId := range roles {
				parseUint, err := strconv.ParseUint(roleId, 10, 64)
				if err != nil {
					c.JSON(http.StatusOK, gin.H{
						"code": http.StatusForbidden,
						"msg":  "角色不存在",
					})
					c.Abort()
					return
				}
				roleEntity, err := rbac.SysRoleDao.GetRoleForm(parseUint)
				if err != nil {
					c.JSON(http.StatusOK, gin.H{
						"code": http.StatusForbidden,
						"msg":  "没有权限:" + perm,
					})
					c.Abort()
					return
				}

				permList := rbac.SysRoleMenuDao.GetRolePermsList(roleEntity.ID)
				for _, permBo := range permList {
					perms := permBo.Perms
					flag = slice.Contain(perms, perm)
					if flag {
						break
					}
				}
			}
		}
		if !flag {
			c.JSON(http.StatusOK, gin.H{
				"code": http.StatusForbidden,
				"msg":  "没有权限:" + perm,
			})
			c.Abort()
			return
		}
		return
	}
}
